<div class="dropdown pull-right column-selector">
    <button type="button" class="btn btn-sm btn-instagram dropdown-toggle" data-toggle="dropdown">
        <i class="fa fa-table"></i>
        &nbsp;
        <span class="caret"></span>
    </button>
    <ul class="dropdown-menu" role="menu">
        <li>
            <ul>
                @foreach($columns as $key => $label)
                    @php
                        if (empty($visible)) {
                            $checked = 'checked';
                        } else {
                            $checked = in_array($key, $visible) ? 'checked' : '';
                        }
                    @endphp

                    <li class="checkbox icheck">
                        <label>
                            <input type="checkbox" class="column-select-item" value="{{ $key }}" {{ $checked }}/>&nbsp;&nbsp;&nbsp;{{ $label }}
                        </label>
                    </li>
                @endforeach
            </ul>
        </li>
        <li class="divider"></li>
        <li class="text-right">
            <button class="btn btn-sm btn-default column-select-all">{{ __('admin.all') }}</button>&nbsp;&nbsp;
            <button class="btn btn-sm btn-primary column-select-submit">{{ __('admin.submit') }}</button>
        </li>
    </ul>
</div>

<style>
    .column-selector {
        margin-right: 10px;
    }

    .column-selector .dropdown-menu {
        padding: 10px;
        height: auto;
        max-height: 500px;
        overflow-x: hidden;
    }

    .column-selector .dropdown-menu ul {
        padding: 0;
    }

    .column-selector .dropdown-menu ul li {
        margin: 0;
    }

    .column-selector .dropdown-menu label {
        width: 100%;
        padding: 3px;
    }
</style>

<script>
    class ColumnSliding {

        element = null;
        defaults = [];
        selected = [];
        columns = [];

        constructor(selector, defaults) {
            this.defaults = defaults;
            this.element = document.querySelector(selector);
            Array.from(this.element.children).forEach((el, i) => {
                el.setAttribute("draggable", "true");
                el.setAttribute("data-index", i);
            });
            this.registerButtonEvent().registerDragEvent();
        }

        registerButtonEvent() {
            let button = this.element.parentElement.parentElement.querySelector('.column-select-submit');
            button.addEventListener('click', () => {
                this.selected = [];
                this.columns = [];
                let inputs = this.element.querySelectorAll('input.column-select-item');
                inputs?.forEach((el) => {
                    if ($(el).prop('checked')) {
                        this.selected.push(el.value);
                        this.columns.push(el.value + ':1')
                    } else {
                        this.columns.push(el.value + ':0')
                    }
                });
                if (this.selected.length == 0) {
                    return;
                }
                var url = new URL(location);
                // if (selected.sort().toString() == defaults.sort().toString()) {
                if (this.selected.toString() == this.defaults.toString()) {
                    url.searchParams.delete('_columns_');
                } else {
                    url.searchParams.set('_columns_', this.columns.join());
                }

                $.pjax({container: '#pjax-container', url: url.toString()});
            })

            $('.column-select-all').on('click', function () {
                $('.column-select-item').iCheck('check');
                return false;
            });

            $('.column-select-item').iCheck({
                checkboxClass: 'icheckbox_minimal-blue'
            });
            return this;
        }

        registerDragEvent() {
            let el = this.element;
            let sourceEle = null;
            let lastIndex = 0;
            el.addEventListener('dragstart', (e) => {
                e.target.style.opacity = '0.4';
                e.dataTransfer.setData('text/plain', e.target.getAttribute('data-index'));
                lastIndex = Number(e.target.dataset.index);
                sourceEle = e.target;
            });
            el.addEventListener('dragover', (e) => {
                e.preventDefault(); // 允许放置
                e.dataTransfer.dropEffect = 'move'; // 设置可移动的视觉效果
            });
            el.addEventListener('dragenter', (e) => {
                e.target.style.border = '1px dashed #ccc';
                let targetEle = e.target;
                if (e.target.tagName == "LABEL") {
                    targetEle = e.target.parentElement;
                }
                if (targetEle == sourceEle) {
                    return;
                }
                let index = Number(targetEle.dataset.index);
                if (index > lastIndex) {
                    if (targetEle.nextElementSibling) {
                        el.insertBefore(sourceEle, targetEle.nextElementSibling);
                    } else {
                        el.append(sourceEle);
                    }
                } else {
                    el.insertBefore(sourceEle, targetEle);
                }
                lastIndex = index;
            });
            el.addEventListener('dragleave', (e) => {
                e.target.style.border = '';
            });
            el.addEventListener('drop', (e) => {
                e.preventDefault();
                e.target.style.border = '';
                e.dataTransfer.setDragImage(sourceEle, 0, 0);
                this.updateDataIndex();
            });
            el.addEventListener('dragend', (e) => {
                e.target.style.opacity = '1';
            });
            return this;
        }


        updateDataIndex() {
            Array.from(this.element.children).forEach((child, index) => {
                child.dataset.index = index;
            });
            return this;
        }
    }

    $(function () {
        window.column_sliding = new ColumnSliding(".column-selector ul.dropdown-menu ul", @json($defaults));
    });
</script>
